package lbframework.bean.jasperViewer;

import java.awt.Component;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.Vector;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperPrint;
import lbframework.classe.Util;
import lbframework.classe.LBException;
import lbframework.bean.dialog.LBDialog;
import lbframework.bean.fileChooser.LBFileChooser;
import lbframework.bean.label.LBLabel;
import lbframework.remote.ItemComboVO;

public class LBJasperViewerMailGUI extends LBDialog {

    private JasperPrint jasperPrint = null;
    private Vector<String> vAnexo = new Vector();
    private String fileImpressao = null;

    public LBJasperViewerMailGUI(JasperPrint i_jasperPrint) throws Exception {
        initComponents();

        centralizarForm();

        jasperPrint = i_jasperPrint;

        this.setModal(true);

        criarAnexoPdf();

        exibirAnexo();

        cboAnexo.setRenderer(new MyListCellRenderer());
    }

    private void criarAnexoPdf() throws Exception {
        fileImpressao = Util.getRoot() + "LimeiraFol/" + jasperPrint.getName() + ".pdf";
        vAnexo.add(fileImpressao);

        JasperExportManager.exportReportToPdfFile(jasperPrint, fileImpressao);
    }

    private void enviar() throws Exception {
        Util.validarCampoTela(this.getCampoObrigatorio());

        Util.enviarEmail(txtDestinatario.getText(), txtAssunto.getText(), txtMensagem.getText(), vAnexo);

        new File(fileImpressao).delete();

        sair();

        Util.exibirMensagem("Enviado com sucesso!", getTitle());
    }

    private void exibirAnexo() throws Exception {
        cboAnexo.removeAllItems();

        int i = 0;

        for (String oAnexo : vAnexo) {
            String[] anexo = oAnexo.replace("\\", "/").split("/");

            cboAnexo.addItem(new ItemComboVO(i, anexo[anexo.length - 1].toString()));
            cboAnexo.setSize(txtAssunto.getSize());

            i++;
        }
    }

    private void adicionarAnexo() throws Exception {
        LBFileChooser flcAnexo = new LBFileChooser();
        flcAnexo.abrir();

        vAnexo.add(flcAnexo.getArquivo());
        exibirAnexo();
    }

    private void excluirAnexo() throws Exception {
        if (cboAnexo.getSelectedIndex() == -1) {
            throw new LBException(Util.MSG_NENHUM_ITEM_SELECIONADO);
        }

        Util.exibirMensagemConfirmar(Util.MSG_CONFIRMA_EXCLUSAO, getTitle());

        vAnexo.remove(cboAnexo.getSelectedIndex());
        exibirAnexo();
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        vRPanel1 = new lbframework.bean.panel.LBPanel();
        vRLabel1 = new lbframework.bean.label.LBLabel();
        txtDestinatario = new lbframework.bean.textField.LBTextField();
        vRLabel2 = new lbframework.bean.label.LBLabel();
        txtAssunto = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtMensagem = new javax.swing.JTextArea();
        cboAnexo = new lbframework.bean.comboBox.LBComboBox();
        vRLabel3 = new lbframework.bean.label.LBLabel();
        vRPanel2 = new lbframework.bean.panel.LBPanel();
        btnSair = new lbframework.bean.button.LBButton();
        btnEnviar = new lbframework.bean.button.LBButton();
        vRToolBar1 = new lbframework.bean.toolBar.LBToolBar();
        btnEnviar2 = new lbframework.bean.button.LBButton();
        btnAdicionar = new lbframework.bean.button.LBButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Email");
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        vRLabel1.setText("Destinatário:");

        txtDestinatario.setCaixaAlta(false);
        txtDestinatario.setMascara("");
        txtDestinatario.setObrigatorio(true);

        vRLabel2.setText("Assunto:");

        txtAssunto.setColumns(50);

        txtMensagem.setColumns(1000);
        txtMensagem.setFont(new java.awt.Font("Tahoma", 0, 11));
        txtMensagem.setLineWrap(true);
        txtMensagem.setRows(5);
        txtMensagem.setWrapStyleWord(true);
        jScrollPane2.setViewportView(txtMensagem);

        cboAnexo.setMaximumSize(txtAssunto.getSize());
        cboAnexo.setMinimumSize(txtAssunto.getSize());
        cboAnexo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                cboAnexoKeyPressed(evt);
            }
        });

        vRLabel3.setText("Anexo:");

        javax.swing.GroupLayout vRPanel1Layout = new javax.swing.GroupLayout(vRPanel1);
        vRPanel1.setLayout(vRPanel1Layout);
        vRPanel1Layout.setHorizontalGroup(
            vRPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, vRPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(vRPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 453, Short.MAX_VALUE)
                    .addGroup(vRPanel1Layout.createSequentialGroup()
                        .addGroup(vRPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(vRLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(vRLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(vRLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(vRPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtDestinatario, javax.swing.GroupLayout.DEFAULT_SIZE, 381, Short.MAX_VALUE)
                            .addComponent(txtAssunto, javax.swing.GroupLayout.DEFAULT_SIZE, 381, Short.MAX_VALUE)
                            .addComponent(cboAnexo, javax.swing.GroupLayout.DEFAULT_SIZE, 381, Short.MAX_VALUE))))
                .addContainerGap())
        );
        vRPanel1Layout.setVerticalGroup(
            vRPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(vRPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(vRPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(vRLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtDestinatario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(vRPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtAssunto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(vRLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(vRPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cboAnexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(vRLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE)
                .addContainerGap())
        );

        btnSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lbframework/img/sair.png"))); // NOI18N
        btnSair.setText("Sair");
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });

        btnEnviar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lbframework/img/email.png"))); // NOI18N
        btnEnviar.setText("Enviar");
        btnEnviar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEnviarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout vRPanel2Layout = new javax.swing.GroupLayout(vRPanel2);
        vRPanel2.setLayout(vRPanel2Layout);
        vRPanel2Layout.setHorizontalGroup(
            vRPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, vRPanel2Layout.createSequentialGroup()
                .addContainerGap(313, Short.MAX_VALUE)
                .addComponent(btnEnviar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnSair, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        vRPanel2Layout.setVerticalGroup(
            vRPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(vRPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(btnSair, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(btnEnviar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        vRToolBar1.setRollover(true);

        btnEnviar2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lbframework/img/email.png"))); // NOI18N
        btnEnviar2.setToolTipText("Enviar Email");
        btnEnviar2.setFocusable(false);
        btnEnviar2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnEnviar2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnEnviar2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEnviar2ActionPerformed(evt);
            }
        });
        vRToolBar1.add(btnEnviar2);

        btnAdicionar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lbframework/img/anexo.png"))); // NOI18N
        btnAdicionar.setToolTipText("Adicionar anexo");
        btnAdicionar.setFocusable(false);
        btnAdicionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAdicionarActionPerformed(evt);
            }
        });
        vRToolBar1.add(btnAdicionar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(vRPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(vRToolBar1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 485, Short.MAX_VALUE)
                    .addComponent(vRPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(vRToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(vRPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(vRPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnEnviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEnviarActionPerformed
        try {
            this.setWaitCursor();
            enviar();

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, getTitle());

        } finally {
            this.setDefaultCursor();
        }
}//GEN-LAST:event_btnEnviarActionPerformed

    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
        try {
            sair();

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, getTitle());
        }
    }//GEN-LAST:event_btnSairActionPerformed

    private void btnEnviar2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEnviar2ActionPerformed
        try {
            this.setWaitCursor();
            enviar();

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, getTitle());

        } finally {
            this.setDefaultCursor();
        }
    }//GEN-LAST:event_btnEnviar2ActionPerformed

    private void btnAdicionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAdicionarActionPerformed
        try {
            adicionarAnexo();

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, getTitle());
        }
    }//GEN-LAST:event_btnAdicionarActionPerformed

    private void cboAnexoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cboAnexoKeyPressed
        try {
            if (evt.getKeyCode() == KeyEvent.VK_DELETE) {
                excluirAnexo();
            }

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, getTitle());
        }
    }//GEN-LAST:event_cboAnexoKeyPressed

    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        //cboAnexo.setSize(txtAssunto.getWidth(), txtAssunto.getHeight());
        //cboAnexo.update(cboAnexo.getGraphics());
    }//GEN-LAST:event_formComponentResized
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private lbframework.bean.button.LBButton btnAdicionar;
    private lbframework.bean.button.LBButton btnEnviar;
    private lbframework.bean.button.LBButton btnEnviar2;
    private lbframework.bean.button.LBButton btnSair;
    private lbframework.bean.comboBox.LBComboBox cboAnexo;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField txtAssunto;
    private lbframework.bean.textField.LBTextField txtDestinatario;
    private javax.swing.JTextArea txtMensagem;
    private lbframework.bean.label.LBLabel vRLabel1;
    private lbframework.bean.label.LBLabel vRLabel2;
    private lbframework.bean.label.LBLabel vRLabel3;
    private lbframework.bean.panel.LBPanel vRPanel1;
    private lbframework.bean.panel.LBPanel vRPanel2;
    private lbframework.bean.toolBar.LBToolBar vRToolBar1;
    // End of variables declaration//GEN-END:variables

    private String getDescricaoCheckBox() {
        String descricao = "";

        for (int i = 0; i < cboAnexo.getItemCount(); i++) {
            if (!descricao.isEmpty()) {
                descricao += "; ";
            }

            descricao += ((ItemComboVO) cboAnexo.getItemAt(i)).descricao;
        }

        return descricao;
    }

    class MyListCellRenderer implements ListCellRenderer {

        LBLabel label;

        public MyListCellRenderer() {
            label = new LBLabel();
        }

        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            if (index == -1) {
                LBLabel lblCampo = new LBLabel();

                lblCampo.setOpaque(true);
                lblCampo.setText(getDescricaoCheckBox());

                return lblCampo;
            }

            ItemComboVO oItemCombo = (ItemComboVO) value;

            label.setText(oItemCombo.descricao);
            label.setOpaque(true);

            if (isSelected) {
                label.setBackground(UIManager.getColor("ComboBox.selectionBackground"));
            } else {
                if (isEnabled()) {
                    label.setBackground(UIManager.getColor("ComboBox.background"));
                } else {
                    label.setBackground(UIManager.getColor("ComboBox.disabledBackground"));
                }
            }

            if (isSelected) {
                label.setForeground(UIManager.getColor("ComboBox.selectionForeground"));
            } else {
                label.setForeground(UIManager.getColor("ComboBox.foreground"));
            }

            return label;
        }
    }
}
